package com.jxd.dianping.controller;

import com.jxd.dianping.common.BusinessException;
import com.jxd.dianping.common.CommonRes;
import com.jxd.dianping.common.EmBusinessError;
import com.jxd.dianping.model.CategoryModel;
import com.jxd.dianping.model.ShopModel;
import com.jxd.dianping.service.CategoryService;
import com.jxd.dianping.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ShopController {
    @Autowired
    private ShopService shopService;

    @Autowired
    private CategoryService categoryService;

    // 推荐服务 V1.0
    @GetMapping("/shop/recommend")
    public CommonRes recommend(@RequestParam(name = "longitude")BigDecimal longitude,
                               @RequestParam(name = "latitude")BigDecimal latitude) throws BusinessException {
        if (longitude == null || latitude == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        List<ShopModel> recommend = shopService.recommend(longitude, latitude);
        return CommonRes.create(recommend);
    }

    // 搜索服务 V1.0
    @PostMapping("/shop/search")
    public CommonRes search(@RequestParam(name = "longitude")BigDecimal longitude,
                            @RequestParam(name = "latitude")BigDecimal latitude,
                            @RequestParam(name = "keyword")String keyword,
                            @RequestParam(name = "orderby", required = false)Integer orderby,
                            @RequestParam(name = "categoryId", required = false)Integer categoryId,
                            @RequestParam(name = "tags", required = false)String tags) throws BusinessException, IOException {
        if (longitude == null || latitude == null || keyword == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        List<CategoryModel> categoryModels = categoryService.selectAll();
//        List<ShopModel> search = shopService.search(longitude, latitude, keyword, orderby, categoryId, tags);
        List<ShopModel> search = (List<ShopModel>)shopService.searchES(longitude, latitude, keyword, orderby, categoryId, tags).get("shop");
        List<Map<String, Object>> tagsAggregation = shopService.searchGroupByTags(keyword, categoryId);

        Map<String, Object> resMap = new HashMap<>();
        resMap.put("shop", search);
        resMap.put("category",categoryModels);
        resMap.put("tags", tagsAggregation);
        return CommonRes.create(resMap);
    }
}
